<script lang="ts" setup name="warePlaceModelDetail">
import { reactive, onMounted } from "vue";
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from "element-plus";
import { useWarePlaceModelApi } from '/@/api/interacting/warePlaceModel';
import { getUserList } from '/@/api/customer/userList';

const route = useRoute();
const router = useRouter();
const warePlaceModelApi = useWarePlaceModelApi();

const state = reactive({
  loading: false,
  warePlaceData: {} as any, // 库位详细信息
  userList: [] as any[], // 用户列表
  goodsList: [] as any[], // 商品列表
  goodsDataError: false, // 商品数据解析错误标志
});

// 根据用户ID获取用户名称
const getUserName = (userId: any) => {
  if (!userId) return '';
  const user = state.userList.find(item => item.value == userId);
  return user ? user.label : userId;
};

// 解析商品名称JSON数据
const parseGoodsData = (shopName: string) => {
  if (!shopName || !shopName.trim()) {
    console.log('商品数据为空');
    return [];
  }
  
  const trimmedData = shopName.trim();
  console.log('开始解析商品数据:', trimmedData);
  
  try {
    // 尝试解析JSON格式
    const goodsData = JSON.parse(trimmedData);
    console.log('JSON解析成功:', goodsData);
    
    // 如果是数组，确保每个元素都有name属性
    if (Array.isArray(goodsData)) {
      const result = goodsData.map((item, index) => {
        if (typeof item === 'string') {
          return { name: item, value: '', id: index + 1 };
        } else if (typeof item === 'object' && item !== null) {
          // 优先使用goodsName字段，这是数据库中的商品名称字段
          const name = item.goodsName || item.name || item.productName || item.GoodsName || `商品${index + 1}`;
          const value = item.description || item.spec || item.remark || item.value || 
                       (item.Quantity ? `数量: ${item.Quantity}` : '') +
                       (item.Amount ? ` 金额: ${item.Amount}` : '') +
                       (item.UnitPrice ? ` 单价: ${item.UnitPrice}` : '') || '';
          
          return {
            name: name,
            value: value.trim(),
            id: item.goodsId || item.id || index + 1,
            quantity: item.Quantity || item.quantity || '',
            amount: item.Amount || item.amount || '',
            unitPrice: item.UnitPrice || item.unitPrice || ''
          };
        }
        return { name: `商品${index + 1}`, value: '', id: index + 1 };
      }).filter(item => item.name && item.name !== `商品${goodsData.indexOf(item) + 1}`); // 过滤掉默认名称的商品
      
      console.log('数组格式解析结果:', result);
      return result;
    }
    
    // 如果是对象，转换为数组
    if (typeof goodsData === 'object' && goodsData !== null) {
      const result = Object.keys(goodsData).map((key, index) => ({
        name: key,
        value: String(goodsData[key] || ''),
        id: index + 1
      })).filter(item => item.name); // 过滤掉空名称的商品
      
      console.log('对象格式解析结果:', result);
      return result;
    }
    
    // 如果是字符串，作为单个商品处理
    if (typeof goodsData === 'string' && goodsData.trim()) {
      const result = [{ name: goodsData.trim(), value: '', id: 1 }];
      console.log('字符串格式解析结果:', result);
      return result;
    }
    
    console.log('JSON数据格式不支持:', typeof goodsData);
    return [];
  } catch (error: any) {
    console.log('JSON解析失败，尝试其他格式:', error?.message || error);
    
    // 如果不是JSON格式，尝试其他分隔符
    const separators = [',', ';', '|', '\n', '，'];
    for (const separator of separators) {
      if (trimmedData.includes(separator)) {
        const result = trimmedData.split(separator)
          .map(name => name.trim())
          .filter(name => name)
          .map((name, index) => ({
            name,
            value: '',
            id: index + 1
          }));
        
        if (result.length > 0) {
          console.log(`使用分隔符"${separator}"解析结果:`, result);
          return result;
        }
      }
    }
    
    // 单个商品名称
    if (trimmedData) {
      const result = [{ name: trimmedData, value: '', id: 1 }];
      console.log('单个商品解析结果:', result);
      return result;
    }
    
    console.log('无法解析商品数据');
    return [];
  }
};

// 加载基础数据
const loadBaseData = async () => {
  // 加载用户列表
  try {
    const res = await getUserList();
    let userList = res?.data?.result || res?.result || [];
    if (userList.length === 0) {
      userList = res?.data || res || [];
    }
    state.userList = userList.map((item: any) => ({
      ...item,
      value: String(item.value),
      label: item.label
    }));
  } catch (_error) {
    console.error('加载用户列表失败:', _error);
  }
};

// 加载库位详情
const loadWarePlaceDetail = async () => {
  const warePlaceId = route.params.id;
  if (!warePlaceId) {
    ElMessage.error('库位ID不存在');
    router.back();
    return;
  }

  state.loading = true;
  try {
    const res = await warePlaceModelApi.detail(warePlaceId);
    state.warePlaceData = res.data.result || {};
    console.log('库位详情数据:', state.warePlaceData);
    
    // 解析商品数据 - 从数据库的shopName字段获取JSON字符串
    state.goodsDataError = false;
    if (state.warePlaceData.shopName && state.warePlaceData.shopName.trim()) {
      console.log('原始商品数据:', state.warePlaceData.shopName);
      try {
        state.goodsList = parseGoodsData(state.warePlaceData.shopName);
        console.log('解析后的商品数据:', state.goodsList);
        
        if (state.goodsList.length === 0) {
          console.log('商品数据解析结果为空');
        }
      } catch (error) {
        console.error('商品数据解析失败:', error);
        state.goodsList = [];
        state.goodsDataError = true;
        ElMessage.warning('商品数据格式错误，无法正确解析');
      }
    } else {
      // 没有商品数据时设置为空数组
      state.goodsList = [];
      console.log('该库位暂无商品数据');
    }
  } catch (error) {
    console.error('加载库位详情失败:', error);
    ElMessage.error('加载库位详情失败');
  } finally {
    state.loading = false;
  }
};

// 返回列表页
const goBack = () => {
  router.back();
};

// 页面加载时
onMounted(async () => {
  await loadBaseData();
  await loadWarePlaceDetail();
});
</script>

<template>
  <div class="warePlace-detail-container">
    <el-card shadow="hover" :body-style="{ padding: '20px' }" v-loading="state.loading">
      <!-- 页面头部 -->
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-button type="primary" icon="ele-Back" @click="goBack">返回</el-button>
            <span class="page-title">库位详情</span>
          </div>
        </div>
      </template>

      <div class="detail-content">
        <!-- 库位基本信息 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-title">
              <el-icon><ele-InfoFilled /></el-icon>
              <span>库位信息</span>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="库位编码" label-class-name="detail-label">
              <span class="detail-value">{{ state.warePlaceData.warePlaceCode || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="库位名称" label-class-name="detail-label">
              <span class="detail-value">{{ state.warePlaceData.warePlaceName || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="库位容量" label-class-name="detail-label">
              <span class="detail-value">{{ state.warePlaceData.warePlaceVolume || '-' }} m³</span>
            </el-descriptions-item>
            <el-descriptions-item label="库位主管" label-class-name="detail-label">
              <span class="detail-value">{{ getUserName(state.warePlaceData.userId) || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="库位状态" label-class-name="detail-label">
              <el-tag v-if="state.warePlaceData.warePlaceType" type="success">启用</el-tag>
              <el-tag v-else type="danger">停用</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" label-class-name="detail-label">
              <span class="detail-value">{{ state.warePlaceData.createTime || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="库位备注" :span="2" label-class-name="detail-label">
              <span class="detail-value">{{ state.warePlaceData.warePlaceNote || '-' }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 存储商品信息 -->
        <el-card class="goods-card" shadow="never" style="margin-top: 20px;">
          <template #header>
            <div class="card-title">
              <el-icon><ele-Box /></el-icon>
              <span>存储商品信息</span>
              <el-tag type="info" size="small">共 {{ state.goodsList.length }} 种商品</el-tag>
            </div>
          </template>
          
          <div v-if="state.goodsList.length > 0">
            <el-table :data="state.goodsList" border style="width: 100%" row-key="id">
              <el-table-column type="index" label="序号" align="center" />
              <el-table-column prop="name" label="商品名称" show-overflow-tooltip />
              <el-table-column prop="quantity" label="数量" align="right" show-overflow-tooltip>
                <template #default="scope">
                  {{ scope.row.quantity || '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice" label="单价" align="right" show-overflow-tooltip>
                <template #default="scope">
                  {{ scope.row.unitPrice || '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="总金额" align="right" show-overflow-tooltip>
                <template #default="scope">
                  {{ scope.row.amount || '-' }}
                </template>
              </el-table-column>
              <el-table-column label="存储状态" align="center">
                <template #default="scope">
                  <el-tag type="success" size="small">存储中</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <el-empty v-else-if="state.goodsDataError" description="商品数据格式错误，无法正确显示" />
          <el-empty v-else description="该库位暂无商品" />
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.warePlace-detail-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      display: flex;
      align-items: center;
      gap: 15px;

      .page-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .detail-content {
    .info-card, .goods-card {
      :deep(.el-card__header) {
        background-color: #f8f9fa;
        border-bottom: 1px solid #e4e7ed;
      }

      .card-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
        font-size: 16px;
        color: #303133;

        .el-icon {
          color: #409eff;
        }
      }
    }

    .goods-card {
      .card-title {
        justify-content: space-between;
        width: 100%;
        
        .el-tag {
          margin-left: auto;
        }
      }

      :deep(.el-table) {
        .el-table__header {
          background-color: #fafafa;
        }
      }
    }
  }

  // 详情描述样式
  :deep(.el-descriptions) {
    .detail-label {
      width: 120px;
      background-color: #fafafa;
      font-weight: 600;
    }

    .detail-value {
      color: #606266;
    }
  }
}
</style>
